package com.babylove.inventory.service.impl;

import com.alibaba.fastjson.JSON;
import com.babylove.common.core.enums.ResponseCode;
import com.babylove.common.core.exception.CustomException;
import com.babylove.common.core.utils.SecurityUtils;
import com.babylove.common.core.utils.StringUtils;
import com.babylove.common.redis.service.RedisService;
import com.babylove.inventory.domain.InvStore;
import com.babylove.inventory.mapper.InvStoreMapper;
import com.babylove.inventory.service.InvStoreService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 仓库表 服务实现类
 * </p>
 *
 * @author caoqingwen
 * @since 2021-01-29
 */
@Service
public class InvStoreServiceImpl implements InvStoreService {

    private static final Logger log = LoggerFactory.getLogger(InvStoreServiceImpl.class);

    @Resource
    private InvStoreMapper storeMapper;


    @Autowired
    private RedisService redisService;


    /**
     * 获取仓库列表
     *
     * @param store
     * @return
     */
    @Override
    public List<InvStore> selectStoreList(InvStore store) {
        return storeMapper.selectStoreList(store);
    }


    /**
     * 新增仓库
     *
     * @param store
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int addStore(InvStore store) {
        log.info("新增仓库参数：{}", JSON.toJSONString(store));
        InvStore invStore = new InvStore();
        invStore.setName(store.getName());
        List<InvStore> invStores = storeMapper.selectStoreList(invStore);
        if (CollectionUtils.isNotEmpty(invStores)) {
            throw new CustomException(ResponseCode.STORE_IS_EXIST);
        }

        store.setCode(generatorCode());
        store.setCreateTime(new Date());
        store.setCreateBy(SecurityUtils.getUsername());

        return storeMapper.insertSelective(store);
    }


    /**
     * 仓库详情
     *
     * @param id
     * @return
     */
    @Override
    public InvStore selectInfo(Long id) {
        InvStore invStore = storeMapper.selectByPrimaryKey(id);
        if (invStore == null) {
            throw new CustomException(ResponseCode.STORE_IS_NOT_EXIST);
        }
        return invStore;
    }


    /**
     * 更新仓库
     *
     * @param store
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int updateStore(InvStore store) {
        InvStore invStore = storeMapper.selectByPrimaryKey(store.getId());
        if (invStore == null) {
            throw new CustomException(ResponseCode.STORE_IS_NOT_EXIST);
        }

        store.setUpdateBy(SecurityUtils.getUsername());
        store.setUpdateTime(new Date());
        return storeMapper.updateByPrimaryKeySelective(store);
    }


    /**
     * 删除仓库
     *
     * @param storeIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int deleteStore(Long[] storeIds) {
        return storeMapper.deleteByIds(storeIds);
    }


    /**
     * 更新状态
     *
     * @param store
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int changeStatus(InvStore store) {
        InvStore invStore = storeMapper.selectByPrimaryKey(store.getId());
        if (invStore == null) {
            throw new CustomException(ResponseCode.STORE_IS_NOT_EXIST);
        }
        store.setUpdateBy(SecurityUtils.getUsername());
        store.setUpdateTime(new Date());
        return storeMapper.updateByPrimaryKeySelective(store);
    }

    private String generatorCode() {
        String code = "CK-";
        //加分布式锁
        if (redisService.setIfAbsent("INV-STORE-CODE", "1", 3, TimeUnit.SECONDS)) {
            String maxCode = storeMapper.selectMaxCode();
            if (StringUtils.isNotBlank(maxCode)) {
                //CK-0001
                Integer num = Integer.parseInt(maxCode.substring(3));
                code = code + (String.format("%04d", num + 1));
            } else {
                code = code + "0001";
            }
            return code;
        } else {
            throw new CustomException("系统新建仓库中,请稍等！");
        }
    }
}
